package com.group3.service.mqservice;

import com.alibaba.fastjson.JSON;
import com.group3.Feign.OrderServiceFeign;
import com.group3.model.Order;
import com.group3.model.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Service
@RocketMQMessageListener(topic = "user-recommend", consumerGroup = "notification-user-recommend-group")
public class NotificationUserRecommendService implements RocketMQListener<User> {


    @Autowired
    OrderServiceFeign orderServiceFeign;

    @Override
    public void onMessage(User user) {
        List<Order> orders = orderServiceFeign.getOrderListbyUid(user.getUid());
        Map<String, Integer> productCountMap = new HashMap<>();

        for (Order order : orders) {
            String productName = order.getPname();
            int quantity = order.getNumber();

            productCountMap.put(productName, productCountMap.getOrDefault(productName, 0) + quantity);
        }

        // 找出购买数量最多的商品
        Optional<Map.Entry<String, Integer>> maxEntry = productCountMap.entrySet()
                .stream()
                .max(Map.Entry.comparingByValue());

        if (maxEntry.isPresent()) {
            String mostFrequentProduct = maxEntry.get().getKey();
            int totalQuantity = maxEntry.get().getValue();
            log.info("用户 {} 为您推荐的商品是: {}，曾今购买过 {} 次", user.getUsername(), mostFrequentProduct, totalQuantity);
        } else {
            log.info("用户 {} 没有购买过任何商品", user.getUsername());
        }
    }

}
